package cn.tedu.es.es;

import cn.tedu.es.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Amos
 * @date 2022/5/3
 * Criteria API
 * - Criteria 条件对象
 * 用来封装搜索条件
 * - CriteriaQuery 查询对象
 * 封装上面的条件对象，和分页对象
 * - ElasticSearchOperations 搜索操作对象
 * 用来执行上面查询的一个工具对象
 */

@Component
public class StudentSearcher {
    @Autowired
    private ElasticsearchOperations op;

    // 用姓名搜索
    public List<Student> findByName(String key) {
        Criteria c = new Criteria("name");
        c.is(key);
        return search(c);
    }

    // 用出生日期范围搜索
    public List<Student> findByBirthDate(String from, String to) {
        Criteria c = new Criteria("birthData");
        c.between(from, to);
        return search(c);
    }

    private List<Student> search(Criteria c) {
        // 用CriteriaQuery封装Criteria
        CriteriaQuery q = new CriteriaQuery(c);
//        q.setPageable(pageable); // 封装分页参数
        SearchHits<Student> shs = op.search(q, Student.class);
        List<Student> list = new ArrayList<>();
        for (SearchHit<Student> sh : shs) {
            list.add(sh.getContent());
        }
        return list;
    }
}
